package com.cl.base.util;

import com.cl.base.auth.entity.AuthUser;
import com.cl.base.constant.ResultCode;
import com.cl.base.exception.ServiceException;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

@UtilityClass
public class SecurityUtil {
    /**
     * 获取用户
     */
    public AuthUser getLoginUser() {
        try {
            return (AuthUser) getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new ServiceException(ResultCode.GET_USER_ERROR);
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    public static void setAuthentication(Authentication authentication) {
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
}
